/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.event.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.event.entity.BizEvent;
import vip.xiaonuo.biz.modular.event.entity.BizEventUnsub;
import vip.xiaonuo.biz.modular.event.mapper.BizEventUnsubMapper;
import vip.xiaonuo.biz.modular.event.service.BizEventService;
import vip.xiaonuo.biz.modular.event.service.BizEventUnsubService;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 事件-取消订阅Service接口实现类
 *
 * @author levin
 * @date 2023/09/05 17:14
 **/
@Service
@Transactional
public class BizEventUnsubServiceImpl extends ServiceImpl<BizEventUnsubMapper, BizEventUnsub> implements BizEventUnsubService {

    @Resource
    private BizEventService bizEventService;

    @Override
    public String cfm(String emailId) {
        String result = "";
        //邮件信息
        Map<String,String> emailInfo = this.baseMapper.getEmailInfoById(emailId);
        if(null!=emailInfo){
            String eventId = emailInfo.get("EVENT_ID");
            String userId = emailInfo.get("USER_ID");
            //事件信息
            BizEvent eventInfo = bizEventService.getById(emailInfo.get("EVENT_ID"));
            if (eventInfo != null) {
                result = eventInfo.getEventTitle();
                //查询是否记录
                QueryWrapper<BizEventUnsub> queryWrapper = new QueryWrapper();
                queryWrapper.eq("EMAIL_ID",emailId);
                queryWrapper.eq("EVENT_ID", eventId);
                queryWrapper.eq("EVENT_USER_ID", userId);
                queryWrapper.eq("DELETE_FLAG", "NOT_DELETE");
                BizEventUnsub unsubInfo = this.baseMapper.selectOne(queryWrapper);
                if (unsubInfo == null) {
                    //有人才插入
                    if (StringUtils.isNotBlank(userId)) {
                        BizEventUnsub entity = new BizEventUnsub();
                        entity.setEmailId(emailId);
                        entity.setEventId(eventId);
                        entity.setEventCode(eventInfo.getEventCode());
                        entity.setEventTitle(eventInfo.getEventTitle());
                        entity.setEventUserId(userId);
                        this.baseMapper.insert(entity);
                    }
                }
            }
        }
        return result;
    }
}
